package com.llkj.qingnianguoxue.base;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.PowerManager;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.http.AnsynHttpRequest;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.playservice.AppCache;
import com.llkj.qingnianguoxue.playservice.Music;
import com.llkj.qingnianguoxue.playservice.OnPlayerEventListener;
import com.llkj.qingnianguoxue.playservice.PlayService;
import com.llkj.qingnianguoxue.util.AppManager;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.Utils;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class BaseActivity extends AppCompatActivity implements AnsynHttpRequest.ObserverCallBack, OnPlayerEventListener {
    protected static final int REQUEST_LOGIN_CODE = 9976;
    public final int TSATUSBAR_TYPE_WHITE_TEXT = 1;
    public final int TSATUSBAR_TYPE_BLACK_TEXT = 2;
    private Dialog waitDialog;
    /**
     * 标记标题左右两边的类型:文字
     */
    protected final int TITLE_TYPE_TEXT = 0;
    /**
     * 标记标题左右两边的类型:图片
     */
    protected final int TITLE_TYPE_IMG = 1;
    protected RelativeLayout rlTitle;
    protected TextView tvTitle;
    protected LinearLayout llLeft, llRight;
    protected ImageView ivRight;
    protected TextView tvLeft, tvRight;
    protected View titleLineBottom;
    protected LayoutInflater baseInflater;
    public int statusBarHeight;
    //    protected SystemBarTintManager systemBarTintManager;
    private ServiceConnection mPlayServiceConnection;
    protected Handler mHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        statusBarHeight = Utils.getStatusBarHeight(this);
        super.onCreate(savedInstanceState);
//        systemBarTintManager = Utils.setStatusBarFontColor(this, true);
        baseInflater = LayoutInflater.from(this);
        AppManager.getInstance().addActivity(this);

        if (AppCache.getPlayService() == null) {
            startService();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    bindService();
                }
            }, 1000);
        } else {
            getPlayService().setOnPlayEventListener(this);
        }
    }

    public void initStatusbar(int satusBarType, View topView, int statusBarColor) {
        LinearLayout.LayoutParams layoutParamsLinearLayout = null;
        RelativeLayout.LayoutParams layoutParamsRelativeLayout = null;
        ConstraintLayout.LayoutParams layoutParamsConstraintLayout = null;
        FrameLayout.LayoutParams layoutParamsFrameLayout = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果系统版本是6.0以上，则将状态栏设置为白底黑字并且全屏
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            switch (satusBarType) {
                case TSATUSBAR_TYPE_WHITE_TEXT:
                    option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                    break;
                case TSATUSBAR_TYPE_BLACK_TEXT:
                    option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                    break;
                default:
                    break;
            }
            decorView.setSystemUiVisibility(option);
            if (statusBarColor != -1) {
                getWindow().setStatusBarColor(getResources().getColor(statusBarColor));
            }
            if (topView != null) {
                if (topView.getParent() instanceof LinearLayout) {
                    layoutParamsLinearLayout = (LinearLayout.LayoutParams) topView.getLayoutParams();
                    layoutParamsLinearLayout.topMargin = DisplayUtil.getStatusHeight(this);
                } else if (topView.getParent() instanceof RelativeLayout) {
                    layoutParamsRelativeLayout = (RelativeLayout.LayoutParams) topView.getLayoutParams();
                    layoutParamsRelativeLayout.topMargin = DisplayUtil.getStatusHeight(this);
                } else if (topView.getParent() instanceof ConstraintLayout) {
                    layoutParamsConstraintLayout = (ConstraintLayout.LayoutParams) topView.getLayoutParams();
                    layoutParamsConstraintLayout.topMargin = DisplayUtil.getStatusHeight(this);
                } else if (topView.getParent() instanceof FrameLayout) {
                    layoutParamsFrameLayout = (FrameLayout.LayoutParams) topView.getLayoutParams();
                    layoutParamsFrameLayout.topMargin = DisplayUtil.getStatusHeight(this);
                }
            }

        } else {
            if (layoutParamsLinearLayout != null) {
                layoutParamsLinearLayout.topMargin = 0;
            } else if (layoutParamsRelativeLayout != null) {
                layoutParamsRelativeLayout.topMargin = 0;
            } else if (layoutParamsConstraintLayout != null) {
                layoutParamsConstraintLayout.topMargin = 0;
            }else if (layoutParamsFrameLayout != null) {
                layoutParamsFrameLayout.topMargin = 0;
            }
        }
    }

    /**
     * 全局等待对话框
     */
    public void loadWaitDialog() {
        initWaitDialog();
    }

    private void initWaitDialog() {
        try {
//            this.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
                    if (waitDialog == null || !waitDialog.isShowing()) {
                        View view = LayoutInflater.from(BaseActivity.this).inflate(R.layout.dialog_load_wait, null);
                        waitDialog = DialogUtil.getDialog(BaseActivity.this, view);
                        waitDialog.setCanceledOnTouchOutside(false);
                        waitDialog.show();
                    }
//                }
//            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void dismissWaitDialog() {
        try {
//            this.runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (waitDialog != null && waitDialog.isShowing()) {
                        waitDialog.dismiss();
                        waitDialog = null;
                    }
                }
            },1000);
//                }
//            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        acquireWakeLock();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        dismissWaitDialog();
        StringUtils.hideSoftKeyboard(this);
        try {
            if (getPlayService().isPlaying()) {
                getPlayService().stop();
            }
        } catch (Exception e) {
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        OkHttpUtils.getInstance().cancelTag(this);
        AppManager.getInstance().removeActivity(this);
        if (null != mPlayServiceConnection) {
            unbindService(mPlayServiceConnection);
        }
//        releaseWakeLock();
        super.onDestroy();
    }

    private PowerManager.WakeLock wakeLock = null;

    /**
     * 获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行
     */
    protected void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, getClass()
                    .getCanonicalName());
            if (null != wakeLock) {
                Log.i("Log", "call acquireWakeLock");
                wakeLock.acquire();
            }
        }
    }

    // 释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock && wakeLock.isHeld()) {
            Log.i("Log", "call releaseWakeLock");
            wakeLock.release();
            wakeLock = null;
        }
    }

    /**
     * 需在setContentView方法之后调用. 设置后,如果不对左侧的事件进行监听,默认的点击事件是结束当前界面.
     * <p/>
     * 标题传资源id和字符串皆可.
     * <p/>
     * 如果某一侧显示的是图片,则那一侧只能传对应的图片资源id.如果是文字,则资源id和字符串皆可.
     *
     * @param title     标题
     * @param left      是否显示左侧的部分
     * @param leftType  左侧的类型
     * @param l         左侧部分内容
     * @param right     是否显示右侧的部分
     * @param rightType 右侧的类型
     * @param r         右侧部分的内容
     */

    protected void setTitle(Object title, boolean left, int leftType, Object l,
                            boolean right, int rightType, Object r) {
        try {
            rlTitle = (RelativeLayout) findViewById(R.id.rl_title);
            tvTitle = (TextView) findViewById(R.id.tv_title);
            tvLeft = (TextView) findViewById(R.id.tv_title_left);
            llLeft = (LinearLayout) findViewById(R.id.ll_title_left);
            ImageView ivLeft = (ImageView) findViewById(R.id.iv_title_left);
            tvRight = (TextView) findViewById(R.id.tv_title_right);
            ivRight = (ImageView) findViewById(R.id.iv_title_right);
            llRight = (LinearLayout) findViewById(R.id.ll_title_right);
            titleLineBottom = findViewById(R.id.line_bottom);
            if (title != null && title instanceof String) {
                if (!TextUtils.isEmpty((String) title)) {
                    tvTitle.setVisibility(View.VISIBLE);
                    tvTitle.setText((String) title);
                } else {
                    tvTitle.setVisibility(View.INVISIBLE);
                }
            } else if (title != null && title instanceof Integer) {
                if (((Integer) title) > 0) {
                    tvTitle.setVisibility(View.VISIBLE);
                    tvTitle.setText((Integer) title);
                } else {
                    tvTitle.setVisibility(View.INVISIBLE);
                }
            }
            if (left) {
                llLeft.setVisibility(View.VISIBLE);
                registerBack();
                if (leftType == TITLE_TYPE_TEXT) {
                    ivLeft.setVisibility(View.GONE);
                    tvLeft.setVisibility(View.VISIBLE);
                    if (l instanceof String) {
                        tvLeft.setText((String) l);
                    } else if (l instanceof Integer) {
                        tvLeft.setText((Integer) l);
                    }
                } else if (leftType == TITLE_TYPE_IMG) {
                    ivLeft.setVisibility(View.VISIBLE);
                    tvLeft.setVisibility(View.GONE);
                    if (l instanceof Integer) {
                        ivLeft.setImageResource((Integer) l);
                    }

                }
            } else {
                llLeft.setVisibility(View.INVISIBLE);
            }
            if (right) {
                llRight.setVisibility(View.VISIBLE);
                rightDo();
                if (rightType == TITLE_TYPE_TEXT) {
                    ivRight.setVisibility(View.GONE);
                    tvRight.setVisibility(View.VISIBLE);
                    if (r instanceof String) {
                        tvRight.setText((String) r);
                    } else if (r instanceof Integer) {
                        tvRight.setText((Integer) r);
                    }
                } else if (rightType == TITLE_TYPE_IMG) {
                    ivRight.setVisibility(View.VISIBLE);
                    tvRight.setVisibility(View.GONE);
                    if (r instanceof Integer) {
                        ivRight.setImageResource((Integer) r);
                    }
                }
            } else {
                llRight.setVisibility(View.INVISIBLE);
            }

        } catch (Exception e) {

        }
    }

    /**
     * 设置点击左上角的返回事件.默认是finish界面
     */
    private void registerBack() {
        LinearLayout llLeft = (LinearLayout) findViewById(R.id.ll_title_left);
        llLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                leftDoWhat();
            }
        });
    }

    /**
     * 设置点击右上角的返回事件.
     */
    private View rightDo() {
        LinearLayout llRight = (LinearLayout) findViewById(R.id.ll_title_right);
        llRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rightDoWhat();
            }
        });
        return llRight;
    }

    protected void rightDoWhat() {

    }

    protected void leftDoWhat() {
        StringUtils.hideSoftKeyboard(this);
        try {
            if (getPlayService().isPlaying()) {
                getPlayService().stop();
            }
        } catch (Exception e) {
        }
        finish();
    }

    protected Dialog dialogConfirm(String title, String content, String leftBtnName, String rightBtnName) {
        View dialogView = baseInflater.inflate(R.layout.dialog_confirm, null);
        final Dialog dialog = DialogUtil.showDialogCenter(this, dialogView, 300);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.dialog_title);
        TextView tvContent = (TextView) dialogView.findViewById(R.id.dialog_content);
        TextView leftBtn = (TextView) dialogView.findViewById(R.id.dialog_left_btn);
        TextView rigntBtn = (TextView) dialogView.findViewById(R.id.dialog_right_btn);
        if (!StringUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        if (!StringUtils.isEmpty(content)) {
            tvContent.setText(content);
            tvContent.setVisibility(View.VISIBLE);
        }
        if (!StringUtils.isEmpty(leftBtnName)) {
            leftBtn.setText(leftBtnName);
        }
        if (!StringUtils.isEmpty(rightBtnName)) {
            rigntBtn.setText(rightBtnName);
        }
        leftBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialogLeftBtn();
            }
        });
        rigntBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialogRightBtn();
            }
        });
        return dialog;
    }

    protected void dialogLeftBtn() {

    }

    protected void dialogRightBtn() {

    }

    protected Dialog dialogPrompt(String title, String content, String rightBtnName) {
        View dialogView = baseInflater.inflate(R.layout.dialog_prompt, null);
        final Dialog dialog = DialogUtil.showDialogCenter(this, dialogView, 300);
        TextView tvTitle = (TextView) dialogView.findViewById(R.id.dialog_title);
        TextView tvContent = (TextView) dialogView.findViewById(R.id.dialog_content);
        TextView rigntBtn = (TextView) dialogView.findViewById(R.id.dialog_right_btn);
        if (!StringUtils.isEmpty(title)) {
            tvTitle.setText(title);
        }
        if (!StringUtils.isEmpty(content)) {
            tvContent.setText(content);
            tvContent.setVisibility(View.VISIBLE);
        }
        if (!StringUtils.isEmpty(rightBtnName)) {
            rigntBtn.setText(rightBtnName);
        }
        rigntBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                dialogRightBtn();
            }
        });
        return dialog;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    protected void onhttpSuccess(String data, int method) {
        dismissWaitDialog();
    }

    protected void onhttpFailed(String message, int method) {
        dismissWaitDialog();
        if (!StringUtils.isEmpty(message)) {
            ToastUtil.makeShortText(this, message);
        }
    }

    protected void onhttpFailed(String data, String message, int method) {
        dismissWaitDialog();
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(BaseActivity.this, clz));
    }

    /**
     * 携带数据页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 携带数据页面跳转并且有请求码
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void handleResult(String data, int encoding, int method) {
        switch (encoding) {
            case AnsynHttpRequest.SUCCESS_HTTP:
                try {
                    if (method == HttpMethod.HTTP_YOUR_URL) {
                        onhttpSuccess(data, method);
                        return;
                    }
                    JSONObject jsonObject = new JSONObject(data);
                    if (jsonObject.has("state") && jsonObject.getInt("state") == 1) {
                        onhttpSuccess(data, method);
                    } else {
                        String message = jsonObject.getString("message");
                        if("此账户已在其他地方登陆".equals(message)){
                            MyApplication.getInstance().sputil.put(ConstantUserInfo.ISLOGIN, false);
                            MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_ID, "");
                            Intent intent = new Intent(this, LoginActivity.class);
                            intent.putExtra("login_out", "2");
                            startActivity(intent);
                        }
                        onhttpFailed(message, method);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    onhttpFailed(getResources().getString(R.string.response_result), method);
                }
                break;
            case AnsynHttpRequest.FAILURE_HTTP:
                onhttpFailed(getResources().getString(R.string.response_result), method);
                break;
            case AnsynHttpRequest.FAILURE_NETWORK:
                onhttpFailed(null, method);
                break;
        }
    }

    protected void login() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, REQUEST_LOGIN_CODE);
    }

    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null != msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null != msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.create().show();
    }

    public PlayService getPlayService() {
        PlayService playService = AppCache.getPlayService();
        if (playService == null) {
            throw new NullPointerException("play service is null");
        }
        return playService;
    }

    private void startService() {
        Intent intent = new Intent(this, PlayService.class);
        startService(intent);
    }

    private void bindService() {
        Intent intent = new Intent();
        intent.setClass(this, PlayService.class);
        mPlayServiceConnection = new PlayServiceConnection();
        bindService(intent, mPlayServiceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onPublish(int progress) {
        dismissWaitDialog();
        onPublicMusic(progress);
    }

    protected void onPublicMusic(int progress) {

    }

    @Override
    public void onBufferingUpdate(int percent) {
    }

    @Override
    public void onChange(Music music) {
    }

    @Override
    public void onPlayerPause() {
    }

    @Override
    public void onPlayerResume() {
    }

    @Override
    public void onTimer(long remain) {
    }

    @Override
    public void onMusicListUpdate() {
    }

    @Override
    public void onPrepared(MediaPlayer mp) {

    }

    private class PlayServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            final PlayService playService = ((PlayService.PlayBinder) service).getService();
            AppCache.setPlayService(playService);
            getPlayService().setOnPlayEventListener(BaseActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    public void myFinish(){
        try {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                    myToast();
                }
            },1500);
        }catch (Exception e){}
    }

    protected void myToast(){

    }

    protected void myToastDelay(final String content){
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ToastUtil.makeLongText(BaseActivity.this,content);
            }
        },1000);
    }
}
